﻿

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

using System.Runtime.InteropServices;
using System.Text;
using TImSdk.Util;

/*
* Copyright:南京新广云信息技术有限公司
* FileName: NativeTIm
* Author: Alours
* Date: 2020/03/20 22:14
* Description: 腾讯IMSdk封装C++ 供C# 调用
* History:
* <author>    <time>    <version>    <desc>
* alours        2020/03/21  1.0      增加 注册回调
*  Remark:所有的回调事件通知要改成IntPtr接受
*  因为c++ char* 用string接口或出现乱码,导致不是一个完整的json串
*  Marshal.PtrToStringAnsi 此方法也不行,必须获取原始内存数据,在转UTF-8
*/
namespace TImSdk
{
    public class TImSdkService
    {
        private string configJsonPath = $"{Environment.CurrentDirectory}\\Config.json";
        private ConfigSetting configSetting { get; set; }
        private static object lockobj = new object();
        private static TImSdkService mInstance;
        #region 接口
        /// <summary>
        /// 离线通知
        /// </summary>
        public ITIMKickedOfflineCallabck tIMKickedOfflineCallabck { get; set; }
        /// <summary>
        /// 会话通知
        /// </summary>
        public ITIMConvCallback tIMConvCallback { get; set; }
        /// <summary>
        /// 消息
        /// </summary>
        public ITIMsgCallback tIMsgCallback { get; set; }
        /// <summary>
        /// 登录回调
        /// </summary>
        public ITIMLoginCallabck tIMLoginCallabck { get; set; }
        /// <summary>
        /// 关系链
        /// </summary>
        public ITIMRelationShipCallabck tIMRelationShipCallabck { get; set; }
        /// <summary>
        /// 用户资料
        /// </summary>
        public ITIMProfileCallback tIMProfileCallback { get; set; }
        /// <summary>
        /// 下载
        /// </summary>
        public ITimDownLoadCallBack timDownLoadCallBack { get; set; }
        #endregion

        public void SetConfigJsonPath(string path)
        {
            configJsonPath = path;
        }

        public static TImSdkService GetInstance
        {
            get
            {
                if (mInstance == null)
                {
                    lock (lockobj)
                    {
                        if (mInstance == null)
                        {
                            mInstance = new TImSdkService();
                        }
                    }
                }
                return mInstance;
            }
        }
        public TImSdkService()
        {

            configSetting = Tools.GetConfigSetting<ConfigSetting>(configJsonPath);
        }

        private void UnInitCallbackDelegate()
        {
            //NativeTIm.tIMRemoveRecvNewMsgCallbackDelegate = new NativeTIm.TIMRemoveRecvNewMsgCallbackDelegate(OnTIMRecvNewMsgCallbackEvent);
        }

        #region 初始化

        /// <summary>
        /// 初始化TImSdk
        /// 成功返回0 
        /// </summary>
        /// <returns></returns>
        public DoTIMResult InitTImSdk()
        {
            if (configSetting.sdkInfo == null|| string.IsNullOrEmpty(configSetting.sdkInfo.appKey)|| configSetting.sdkInfo.sdkAppID==0)
                return GetTIMResult(-1, "缺少sdkAppId或appKey");
            else
            {
                var result = SetTImConfig();
                if (result.Code == 0)
                {
                    var json_sdk_config = JsonConvert.SerializeObject(configSetting.sdkConfig);
                    var result2 = NativeTIm.TIMInit(configSetting.sdkInfo.sdkAppID, json_sdk_config);
                    if (result2 == 0)
                    {
                        InitCallbackDelegate();
                        AddListenerCallback();

                    }
                    return GetTIMResult<TIMResult>(result2);
                }
                return result;
            }
        }
        /// <summary>
        /// 卸载SDK
        /// </summary>
        /// <returns></returns>
        public DoTIMResult UnInitTImSdk()
        {

            var result = NativeTIm.TIMUninit();
            return GetTIMResult<TIMResult>(result);

        }
        /// <summary>
        /// 获取TIm版本
        /// </summary>
        /// <returns></returns>
        public string GetTIMGetSDKVersion()
        {
            var result = NativeTIm.TIMGetSDKVersion();
            return PtrToString(result);
        }
        #endregion

        #region 结果
        public static DoTIMResult GetTIMResult<T>(int code)
        {
            return new DoTIMResult(code, code.GetEnumDescription<T>());
        }
        public static DoTIMResult GetTIMResult(int code, string message)
        {
            return new DoTIMResult(code, message);
        }
        #endregion

        #region 网络连接状态
        /// <summary>
        /// 设置网络连接状态监听回调
        /// </summary>
        /// <param name="status">网络状态</param>
        /// <param name="code">值</param>
        /// <param name="desc">描述</param>
        /// <param name="user_data">用户自定义数据</param>
        private static void OnIMNetworkStatusListenerCallbackEvent(TIMNetworkStatus status, int code, string desc, IntPtr user_data)
        {
            Console.WriteLine($"TIMNetworkStatus:{status}code:{code};desc:{desc}");
        }
        #endregion

        #region 被踢下线
        /// <summary>
        /// 被踢下线
        /// </summary>
        /// <param name="user_data"></param>
        private void OnTIMKickedOfflineCallbackEvent(IntPtr user_data)
        {
            Console.WriteLine("被踢下线");
            tIMKickedOfflineCallabck?.OnTIMKickedOfflineNotifyEvent();
        }

        #endregion

        #region 会话
        /// <summary>
        /// 创建会话
        /// </summary>
        /// <param name="conv_id">会话Id</param>
        /// <param name="conv_type">会话类型</param>
        /// <param name="user_data">自定数据</param>
        /// <returns></returns>
        public int IMConvCreate(string conv_id, TIMConvType conv_type)
        {
            NativeTIm.tIMCommCallbackDelegate = new NativeTIm.TIMCommCallbackDelegate(OnIMConvCreateCallBack);
            return NativeTIm.TIMConvCreate(conv_id, conv_type, NativeTIm.tIMCommCallbackDelegate, IntPtr.Zero);
        }
        /// <summary>
        /// 创建会话主动异步返回通知
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnIMConvCreateCallBack(uint code, string desc, string json_params, IntPtr user_data)
        {
            if (code == 0)
            {
                if (!string.IsNullOrEmpty(json_params))
                {
                    var covnInfo = json_params.StringToObject<ConvInfo>();
                    tIMConvCallback?.OnIMConvCreateCallBack(covnInfo);
                    Console.WriteLine("OnIMConvCreateCallBack:code:" + code + ";desc:" + desc + ";json_params=" + json_params);
                }
            }

        }
        /// <summary>
        /// 收到新的会话通知//会话新增/会话删除/会话更新
        /// </summary>
        /// <param name="tIMConvEvent"></param>
        /// <param name="json_conv_array"></param>
        /// <param name="user_data"></param>
        public void OnTIMConvCreateCallBackEvent(TIMConvEvent tIMConvEvent, IntPtr jsonConvArray, IntPtr user_data)
        {
            var json_conv_array = MarshalNativeToManaged(jsonConvArray);
            Console.WriteLine($"tIMConvEvent:{tIMConvEvent},json_conv_array:{json_conv_array}");
            if (!string.IsNullOrEmpty(json_conv_array))
            {
                try
                {
                    var convArr = JsonConvert.DeserializeObject<List<ConvInfo>>(json_conv_array);
                    if (convArr != null && convArr.Count > 0)
                    {
                        tIMConvCallback?.OnNewConvNotify(tIMConvEvent, convArr);
                    };
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"OnTIMConvCreateCallBackEvent:{ex.Message}");
                }

            }

        }


        /// <summary>
        /// 获取本地会话记录
        /// </summary>
        /// <returns></returns>
        public DoTIMResult TIMConvGetLocalConvList()
        {
            var result = NativeTIm.TIMConvGetConvList(NativeTIm.onTIMConvGetLocalConvListCallBackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 获取本地会话记录回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnTIMConvGetLocalConvListCallBack(UInt32 code, string desc, IntPtr jsonParams, IntPtr user_data)
        {
            var json_params = MarshalNativeToManaged(jsonParams);
        }
        /// <summary>
        /// 删除会话
        /// Remark:删除会话,对方会收到会话通知
        /// </summary>
        /// <param name="convId">会话Id</param>
        /// <param name="tIMConvType">会话类型</param>
        /// <returns></returns>
        public DoTIMResult TIMConvDelete(string convId, TIMConvType tIMConvType)
        {
            NativeTIm.tIMCommCallbackDelegate = new NativeTIm.TIMCommCallbackDelegate(TIMConvDeleteCallbackDelegate);
            var result = NativeTIm.TIMConvDelete(convId, tIMConvType, NativeTIm.tIMCommCallbackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 删除会话回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void TIMConvDeleteCallbackDelegate(uint code, string desc, string json_params, IntPtr user_data)
        {

        }
        #endregion

        #region 设置额外的用户配置
        /// <summary>
        /// 设置额外的用户配置
        /// </summary>
        /// <returns></returns>
        public DoTIMResult SetTImConfig()
        {
            var json_set_config = JsonConvert.SerializeObject(configSetting.tIMSetConfig);
            NativeTIm.tIMCommCallbackDelegate = new NativeTIm.TIMCommCallbackDelegate(TIMSetConfigCallbackEvent);
            var result = NativeTIm.TIMSetConfig(json_set_config, NativeTIm.tIMCommCallbackDelegate, IntPtr.Zero);

            return GetTIMResult<TIMResult>(result);

        }
        /// <summary>
        /// 设置额外的用户配置回调
        /// 许多SDK的方法都会出发此回调
        /// </summary>
        /// <param name="code">ERR_SUCC表示成功其他值表示失败</param>
        /// <param name="desc">错误描述字符串</param>
        /// <param name="json_params">Json字符串，不同的接口，Json字符串不一样</param>
        /// <param name="user_data">ImSDK负责透传的用户自定义数据，未做任何处理</param>
        private void TIMSetConfigCallbackEvent(uint code, string desc, string json_params, IntPtr user_data)
        {
            Console.WriteLine("TIMSetConfigCallbackEvent:code:" + code + ";desc:" + desc + ";json_params=" + json_params);
         
        }
        #endregion

        #region 登录/登出
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userId">用户标识</param>
        /// <returns></returns>
        public DoTIMResult Login(string userId, string userSign)
        {
            userSign = new TLSSigAPIv2(configSetting.sdkInfo.sdkAppID, configSetting.sdkInfo.appKey).GenSig(userId);
            var result = NativeTIm.TIMLogin(userId, userSign, NativeTIm.onTIMLoginCallbackDelegate, IntPtr.Zero);

            return GetTIMResult<TIMResult>(result);

        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public DoTIMResult TIMLogout()
        {
            var result = NativeTIm.TIMLogout(NativeTIm.onTIMLoginCallbackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }

        /// <summary>
        /// 回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnTIMLoginCallbackEvent(uint code, string desc, string json_params, IntPtr user_data)
        {
            tIMLoginCallabck?.OnTIMLoginCallback(code, desc);
            
        }
        #endregion

        #region 消息

        /// <summary>
        /// 消息上报已读
        /// </summary>
        /// <param name="conv_id">会话的ID</param>
        /// <param name="conv_type">会话类型</param>
        /// <param name="json_msg_param">消息json字符串</param>
        /// <param name="tIMCommCallbackDelegate">消息上报已读成功与否的回调</param>
        /// <param name="user_data">用户自定义数据</param>
        public void TIMMsgReportReaded(string conv_id, TIMConvType conv_type, string json_msg_param)
        {
            NativeTIm.TIMMsgReportReaded(conv_id, conv_type, json_msg_param, NativeTIm.onTIMSendTIMMsgReportReadedDelegate, IntPtr.Zero);
        }
        /// <summary>
        /// 消息上报已读回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnSendTIMMsgReportReadedCallBack(uint code, string desc, IntPtr jsonParams, IntPtr user_data)
        {
            var json_params = MarshalNativeToManaged(jsonParams);
            Console.WriteLine("OnSendTIMMsgReportReadedCallBack:code:" + code + ";desc:" + desc + ";json_params=" + json_params);
        }
        /// <summary>
        /// 获取指定会话的消息列表。
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="jsonParams"></param>
        /// <param name="user_data"></param>
        public DoTIMResult TIMMsgGetMsgList(string conv_id, TIMConvType tIMConvType, MsgGetMsgListParam msgGetMsg)
        {
            var result = NativeTIm.TIMMsgGetMsgList(conv_id, tIMConvType, JsonConvert.SerializeObject(msgGetMsg).ToUTF8Bytes(),
                NativeTIm.onTIMMsgGetMsgListCallbackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 获取消息回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="jsonParams"></param>
        /// <param name="user_data"></param>
        private void OnTIMMsgGetMsgListCallback(uint code, string desc, IntPtr jsonParams, IntPtr user_data)
        {
            var json_params = MarshalNativeToManaged(jsonParams);
            if (code == 0)
            {
                if (!string.IsNullOrEmpty(json_params))
                {
                    //Console.WriteLine("code:" + code + ";desc:" + desc + ";json_params=" + json_params);
                    try
                    {
                        var messInfo = JsonConvert.DeserializeObject<List<Message>>(json_params);
                        tIMsgCallback?.OnTIMMsgGetMsgList(messInfo);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"OnTIMRecvNewMsgCallbackEvent:{ex.Message}");
                    }
                }

            }

        }
        /// <summary>
        /// 发送文本信息
        /// </summary>
        /// <param name="convId"></param>
        /// <param name="tIMConvType"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public DoTIMResult TIMMsgSendTextMsg(string convId, TIMConvType tIMConvType, string content, int mode = 0)
        {
            var textElem = new TextElem
            {
                Elem_Type = TIMElemType.kTIMElem_Text,
                Text_Elem_Content = content
            };
            return TIMMsgSendNewMsg(convId, tIMConvType, textElem, mode);
        }
        /// <summary>
        /// 发送声音
        /// </summary>
        /// <param name="convId"></param>
        /// <param name="tIMConvType"></param>
        /// <param name="soundPath"></param>
        /// <param name="size"></param>
        /// <param name="fileTime"></param>
        /// <returns></returns>
        public DoTIMResult TIMMsgSendSoundMsg(string convId, TIMConvType tIMConvType, string soundPath, long size, int fileTime, int mode = 0)
        {
            var soundElem = new SoundElem
            {
                Elem_Type = TIMElemType.kTIMElem_Sound,
                Sound_Elem_File_Path = soundPath
            };
            return TIMMsgSendNewMsg(convId, tIMConvType, soundElem);
        }
        /// <summary>
        /// 发送图片
        /// </summary>
        /// <param name="convId"></param>
        /// <param name="tIMConvType"></param>
        /// <param name="soundPath"></param>
        /// <param name="size"></param>
        /// <param name="fileTime"></param>
        /// <returns></returns>
        public DoTIMResult TIMMsgSendImageMsg(string convId, TIMConvType tIMConvType, string imagePath, int mode = 0)
        {
            var elem = new ImageElem
            {
                Elem_Type = TIMElemType.kTIMElem_Image,
                Image_Elem_Orig_Path = imagePath,
                Image_Elem_Level = TIMImageLevel.kTIMImageLevel_Compression,
                Image_Elem_Format = 1
            };
            return TIMMsgSendNewMsg(convId, tIMConvType, elem);
        }
        /// <summary>
        /// 发送视频
        /// </summary>
        /// <param name="convId"></param>
        /// <param name="tIMConvType"></param>
        /// <param name="imagePath"></param>
        /// <param name="imageWidth"></param>
        /// <param name="imageHeight"></param>
        /// <param name="imageSize"></param>
        /// <param name="filePath"></param>
        /// <param name="fileSize"></param>
        /// <param name="durtion"></param>
        /// <param name="fileExt"></param>
        /// <returns></returns>
        public DoTIMResult TIMMsgSendViedoMsg(string convId, TIMConvType tIMConvType,
            string imagePath, int imageWidth, int imageHeight, int imageSize,
            string filePath, int fileSize, int durtion, string fileExt, int mode = 0)
        {
            var elem = new VideoElem
            {
                Elem_Type = TIMElemType.kTIMElem_Video,
                Video_Elem_Video_Type = fileExt,
                Video_Elem_Video_Size = fileSize,
                Video_Elem_Video_Duration = durtion,
                Video_Elem_Video_Path = filePath,
                Video_Elem_Image_Type = "1",
                Video_Elem_Image_Size = imageSize,
                Video_Elem_Image_Width = imageWidth,
                Video_Elem_Image_Height = imageHeight,
                Video_Elem_Image_Path = imagePath
            };
            return TIMMsgSendNewMsg(convId, tIMConvType, elem);
        }
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="convId"></param>
        /// <param name="tIMConvType"></param>
        /// <param name="elem"></param>
        /// <returns></returns>
        public DoTIMResult TIMMsgSendNewMsg(string convId, TIMConvType tIMConvType, Elem elem, int mode = 0)
        {
            Message message = new Message();
            message.Message_Elem_Array = new List<Elem> { elem };
            var result = NativeTIm.TIMMsgSendNewMsg(convId, tIMConvType,
                message.ToJsonString().ToUTF8Bytes(), NativeTIm.onTIMMsgSendNewMsgCallBackDelegate, mode);
            message = null;
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 发送信息回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="jsonParams"></param>
        /// <param name="userData"></param>
        public void OnTIMMsgSendNewMsgCallBack(UInt32 code, string desc, IntPtr jsonParams, int mode)
        {
            var json_params = MarshalNativeToManaged(jsonParams);
            if (code == 0 && json_params != "")
            {
                //Console.WriteLine($"OnTIMMsgSendNewMsgCallBack:{json_params}");
                try
                {
                    var messInfo = JsonConvert.DeserializeObject<Message>(json_params);
                    if (messInfo != null)
                    {
                        var list = new List<Message>();
                        list.Add(messInfo);
                        tIMsgCallback?.OnTIMRecvNewMsg(list);
                        list = null;
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine($"OnTIMMsgSendNewMsgCallBack:{ex.Message}");
                }

            }

        }
        #endregion

        #region 关系链
        /// <summary>
        /// 获取好友列表
        /// </summary>
        /// <returns></returns>
        public DoTIMResult TIMFriendshipGetFriendProfileList()
        {
            var result = NativeTIm.TIMFriendshipGetFriendProfileList(NativeTIm.onTIMFriendshipGetFriendProfileListCallBackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 获取好友列表回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnTIMFriendshipGetFriendProfileListCallBack(uint code, string desc, IntPtr jsonParams, IntPtr user_data)
        {
            if (code == 0)
            {
                var json_params = MarshalNativeToManaged(jsonParams);
                var friendInfos = JsonConvert.DeserializeObject<List<FriendProfile>>(json_params);
                if (friendInfos != null)
                {
                    tIMRelationShipCallabck?.OnTIMFriendshipGetFriendProfileList(friendInfos);
                }
            }
        }
        //"friend_profile_item_remark";               // string,       只写, 修改好友备注
        //"friend_profile_item_group_name_array";     // array string, 只写, 修改好友分组名称列表
        //"friend_profile_item_custom_string_array";  // array [FriendProfileCustemStringInfo](), 只写, 修改[自定义好友字段]
        //"friend_profile_custom_string_info_key";   // string, 只写, 好友自定义资料字段key
        //"friend_profile_custom_string_info_value"; // string, 只写, 好友自定义资料字段value        
        ///<summary>
        /// 修改好友资料
        /// </summary>
        public DoTIMResult TIMFriendshipModifyFriendProfile(string identifier, FriendProfileItem json_modify_friend_info_param)
        {
            var jsonParam = JsonConvert.SerializeObject(
                new
                {
                    friendship_modify_friend_profile_param_identifier = identifier,
                    friendship_modify_friend_profile_param_item = json_modify_friend_info_param
                });
            ;
            var result = NativeTIm.TIMFriendshipModifyFriendProfile(jsonParam.ToUTF8Bytes(), NativeTIm.onTIMFriendshipModifyFriendProfileCallBackDelegate, IntPtr.Zero);

            return GetTIMResult<TIMResult>(result);
        }

        /// <summary>
        /// 修改好友资料回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnTIMFriendshipModifyFriendProfileCallBack(uint code, string desc, string jsonParams, IntPtr user_data)
        {
            if (code == 0)
            {
                //tIMRelationShipCallabck?.TIMFriendshipModifyFriendProfile();
            }
        }

        /// <summary>
        /// 获取好友添加请求未决信息列表
        /// </summary>
        /// <param name="seq">获取未决的起始seq 
        /// 未决列表序列号。建议客户端保存 seq 和未决列表，
        /// 请求时填入 server 返回的 seq。如果 seq 是 server
        /// 最新的，则不返回数据</param>
        public DoTIMResult TIMFriendshipGetPendencyList(int seq = 0, TIMFriendPendencyType tIMFriendPendencyType = TIMFriendPendencyType.FriendPendencyTypeComeIn)
        {
            var search = new FriendshipGetPendencyListParam(seq, tIMFriendPendencyType);
            var result = NativeTIm.TIMFriendshipGetPendencyList(search.ToJsonString().ToUTF8Bytes(),
                NativeTIm.onTIMFriendshipGetPendencyListCallBackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 获取好友添加请求未决信息列表回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="jsonParams"></param>
        /// <param name="user_data"></param>
        private void OnTIMFriendshipGetPendencyListCallBack(uint code, string desc, IntPtr jsonParams, IntPtr user_data)
        {
            if (code == 0)
            {
                var json_params = MarshalNativeToManaged(jsonParams);
                var pendencyPage = JsonConvert.DeserializeObject<PendencyPage>(json_params);
                if (pendencyPage != null)
                {
                    tIMRelationShipCallabck?.OnTIMFriendshipGetPendencyList(pendencyPage);
                }
            }
        }

        /// <summary>
        /// 添加好友
        /// </summary>
        /// <param name="FriendshipAddFriendParam">参数</param>
        /// <returns></returns>
        public DoTIMResult TIMFriendshipAddFriend(FriendshipAddFriendParam friendshipAddFriend)
        {
            var result = NativeTIm.TIMFriendshipAddFriend(friendshipAddFriend.ToJsonString().ToUTF8Bytes(), NativeTIm.onTIMFriendshipAddFriendCallBackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 添加好友回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="jsonParams"></param>
        /// <param name="user_data"></param>
        private void OnTIMFriendshipAddFriendCallBack(uint code, string desc, IntPtr jsonParams, IntPtr user_data)
        {
            if (code == 0)
            {

            }
        }
        /* json_handle_friend_add_param[kTIMFriendResponeIdentifier] = "user1";
        * json_handle_friend_add_param[kTIMFriendResponeAction] = ResponseActionAgreeAndAdd;
        * json_handle_friend_add_param[kTIMFriendResponeRemark] = "I am Captain China";
        * json_handle_friend_add_param[kTIMFriendResponeGroupName] = "schoolmate";*/
        /// <summary>
        /// 处理好友请求
        /// </summary>
        /// <returns></returns>
        public DoTIMResult TIMFriendshipHandleFriendAddRequest(FriendRespone friendRespone)
        {
            NativeTIm.tIMCommCallbackDelegate = new NativeTIm.TIMCommCallbackDelegate(HandleFriendAddRequestCallBack);
            var result = NativeTIm.TIMFriendshipHandleFriendAddRequest(friendRespone.ToJsonString().ToUTF8Bytes(), NativeTIm.tIMCommCallbackDelegate, IntPtr.Zero);
        
            return GetTIMResult<TIMResult>(result);
        }

        private void HandleFriendAddRequestCallBack(uint code, string desc, string json_params, IntPtr user_data)
        {
            Console.WriteLine("HandleFriendAddRequestCallBack");
        }
        /// <summary>
        /// 删除好友
        /// </summary>
        /// <param name="friendshipDeleteFriendParam"></param>
        /// <returns></returns>
        public DoTIMResult TIMFriendshipDeleteFriend(FriendshipDeleteFriendParam friendshipDeleteFriendParam)
        {
            NativeTIm.tIMCommCallbackDelegate = new NativeTIm.TIMCommCallbackDelegate(OnTIMFriendshipDeleteFriendCallBack);
            var result = NativeTIm.TIMFriendshipDeleteFriend(friendshipDeleteFriendParam.ToJsonString().ToUTF8Bytes(),
                NativeTIm.tIMCommCallbackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 删除好友回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnTIMFriendshipDeleteFriendCallBack(uint code, string desc, string json_params, IntPtr user_data)
        {
            Console.WriteLine("OnTIMFriendshipDeleteFriendCallBack");
        }
        #endregion

        #region 用户资料
        /// <summary>
        ///  获取指定用户列表的个人资料
        /// </summary>
        /// <param name="identifierArr">想要获取目标用户资料的identifier列表</param>
        /// <param name="force_update">是否强制更新。false表示优先从本地缓存获取，
        /// 获取不到则去网络上拉取。true表示直接去网络上拉取资料。默认值为false</param>
        /// <param name="Module">那个模样调用的，最好没有中文</param>
        /// <returns></returns>
        public DoTIMResult TIMProfileGetUserProfileList(string[] identifierArr, bool force_update = false, int module = 0)
        {
            var json_get_user_profile_list_param = JsonConvert.SerializeObject(new
            {
                friendship_getprofilelist_param_force_update = force_update,
                friendship_getprofilelist_param_identifier_array = identifierArr
            }).ToUTF8Bytes();
            var result = NativeTIm.TIMProfileGetUserProfileList(json_get_user_profile_list_param, NativeTIm.onTIMProfileGetUserProfileListCallBackDelegate, module);
            return GetTIMResult<TIMResult>(result);
        }

        /// <summary>
        /// 获取指定用户列表的个人资料回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnTIMProfileGetUserProfileListCallBack(uint code, string desc, IntPtr jsonParams, int user_data)
        {
            var json_params = MarshalNativeToManaged(jsonParams);

            if (code == 0)
            {
                Console.WriteLine($"OnTIMProfileGetUserProfileListCallBack:{json_params}");
                var list = json_params.StringToObject<List<UserProfile>>();
                tIMProfileCallback?.GetUserProfileList(list, user_data);


            }
        }
        //"user_profile_item_nick_name";           // string,                           只写, 修改用户昵称
        //"user_profile_item_gender";              // uint [TIMGenderType](),           只写, 修改用户性别
        //"user_profile_item_face_url";            // string,                           只写, 修改用户头像
        //"user_profile_item_self_signature";      // string,                           只写, 修改用户签名
        //"user_profile_item_add_permission";      // uint [TIMProfileAddPermission](), 只写, 修改用户加好友的选项
        //"user_profile_item_location";            // uint,                             只写, 修改位置
        //"user_profile_item_language";            // uint,                             只写, 修改语言
        //"user_profile_item_birthday";            // uint,                             只写, 修改生日
        //"user_profile_item_level";               // uint,                             只写, 修改等级
        //"user_profile_item_role";                // uint,                             只写, 修改角色
        //"user_profile_item_custom_string_array"; // array [UserProfileCustemStringInfo](), 只写, 修改[自定义资料字段]
        //"user_profile_custom_string_info_key";  
        //"user_profile_custom_string_info_value";
        /// <summary>
        /// 修改自己的资料时,目前支持修改的字段请参考 UserProfileItem，一次可更新多个字段。修改自定义字段时填入的 key 值
        /// 可以添加Tag_Profile_Custom_前缀,也可以不添加Tag_Profile_Custom_前缀，当不添加时，SDK 内部会自动添加该前缀
        /// </summary>
        /// <param name="modifyInfo"></param>
        /// <returns></returns>
        public DoTIMResult TIMProfileModifySelfUserProfile(Dictionary<string, object> modifyInfo)
        {
            var result = NativeTIm.TIMProfileModifySelfUserProfile(JsonConvert.SerializeObject(modifyInfo), NativeTIm.onTIMProfileModifySelfUserProfileCallBackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 修改用户加好友的选项
        /// </summary>
        /// <param name="tIMProfileAddPermission"></param>
        /// <returns></returns>
        public DoTIMResult TIMProfileModifySelfUserProfile(int tIMProfileAddPermission)
        {
            var data = new
            {
                user_profile_item_add_permission= (TIMProfileAddPermission)tIMProfileAddPermission
            };
            var result = NativeTIm.TIMProfileModifySelfUserProfile(JsonConvert.SerializeObject(data), NativeTIm.onTIMProfileModifySelfUserProfileCallBackDelegate, IntPtr.Zero);
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 修改自己的资料时回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        private void OnTIMProfileModifySelfUserProfileListCallBack(uint code, string desc, IntPtr jsonParams, IntPtr user_data)
        {
            var json_params = MarshalNativeToManaged(jsonParams);
            Console.WriteLine($"OnTIMProfileModifySelfUserProfileListCallBack:{json_params}");
        }

        #endregion

        #region 元素下载上传
        /// <summary>
        /// 元素下载
        /// </summary>
        /// <param name="messgaeUniqueId">消息Id</param>
        /// <param name="downloadElemParam">下载参数</param>
        /// <param name="savePath">保存地址</param>
        /// <param name="mode">模块</param>
        /// <returns></returns>
        public DoTIMResult TIMMsgDownloadElemToPath(long messgaeUniqueId, DownloadElemParam downloadElemParam, string savePath, string convId)
        {
            //防止出现地址有中文,所以要将savaPath转为byte[]
            //元素Id用于区分是那个下载好了
            var result = NativeTIm.TIMMsgDownloadElemToPath(downloadElemParam.ToJsonString().ToUTF8Bytes(),
                savePath.ToUTF8Bytes(), NativeTIm.onTIMMsgDownloadElemToPathCallbackDelegate, ($"{messgaeUniqueId}|{downloadElemParam.Msg_Download_Elem_Param_Type}|{convId}").ToUTF8Bytes());
            return GetTIMResult<TIMResult>(result);
        }
        /// <summary>
        /// 元素下载回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="json_params"></param>
        /// <param name="user_data"></param>
        public void OnTIMMsgDownloadElemToPathCallback(UInt32 code, string desc, IntPtr jsonParams, IntPtr userData)
        {
            var json_params = MarshalNativeToManaged(jsonParams);
            if (code == 0 && json_params != "")
            {
                MsgDownloadElemResult result = json_params.StringToObject<MsgDownloadElemResult>();
                if (result.Msg_Download_Elem_Result_Current_Size == result.Msg_Download_Elem_Result_Total_Size)
                {
                    var @params = MarshalNativeToManaged(userData).Split('|');
                    timDownLoadCallBack?.DownloadComplate(long.Parse(@params[0]),
                        (TIMDownloadType)Enum.Parse(typeof(TIMDownloadType), @params[1]), @params[2]);
                }
                Console.WriteLine("OnTIMMsgDownloadElemToPathCallback:code:" + code + ";desc:" + desc + ";json_params=" + json_params);
            }

        }

        #endregion

        #region 注册事件通知与通知
        /// <summary>
        /// 注册事件通知与通知
        /// </summary>
        private void InitCallbackDelegate()
        {
            NativeTIm.onTIMLoginCallbackDelegate = new NativeTIm.OnTIMLoginCallbackDelegate(OnTIMLoginCallbackEvent);
            NativeTIm.tIMRecvNewMsgCallbackDelegate = new NativeTIm.TIMRecvNewMsgCallbackDelegate(OnTIMRecvNewMsgCallbackEvent);
            NativeTIm.tIMRemoveRecvNewMsgCallbackDelegate = new NativeTIm.TIMRemoveRecvNewMsgCallbackDelegate(OnTIMRecvNewMsgCallbackEvent);
            NativeTIm.tIMMsgReadedReceiptCallbackDelegate = new NativeTIm.TIMMsgReadedReceiptCallbackDelegate(OnIMMsgReadedReceiptCallbackEvent);
            NativeTIm.tIMMsgRevokeCallbackDelegate = new NativeTIm.TIMMsgRevokeCallbackDelegate(OnIMMsgRevokeCallbackEvent);
            NativeTIm.tIMMsgElemUploadProgressCallbackDelegate = new NativeTIm.TIMMsgElemUploadProgressCallbackDelegate(OnIMMsgElemUploadProgressCallbackEvent);
            NativeTIm.tIMGroupTipsEventCallbackDelegate = new NativeTIm.TIMGroupTipsEventCallbackDelegate(OnIMGroupTipsEventCallbackEvent);
            NativeTIm.tIMConvEventCallbackDelegate = new NativeTIm.TIMConvEventCallbackDelegate(OnTIMConvCreateCallBackEvent);
            NativeTIm.tIMNetworkStatusListenerCallbackDelegate = new NativeTIm.TIMNetworkStatusListenerCallbackDelegate(OnIMNetworkStatusListenerCallbackEvent);
            NativeTIm.tIMKickedOfflineCallbackDelegate = new NativeTIm.TIMKickedOfflineCallbackDelegate(OnTIMKickedOfflineCallbackEvent);
            NativeTIm.tIMUserSigExpiredCallbackDelegate = new NativeTIm.TIMUserSigExpiredCallbackDelegate(OnTIMUserSigExpiredCallbackEvent);
            NativeTIm.tIMOnAddFriendCallbackDelegate = new NativeTIm.TIMOnAddFriendCallbackDelegate(OnTIMOnAddFriendCallbackEvent);
            NativeTIm.tIMOnDeleteFriendCallbackDelegate = new NativeTIm.TIMOnDeleteFriendCallbackDelegate(OnOnDeleteFriendCallbackEvent);
            NativeTIm.tIMUpdateFriendProfileCallbackDelegate = new NativeTIm.TIMUpdateFriendProfileCallbackDelegate(OnTIMUpdateFriendProfileCallbackEvent);
            NativeTIm.tIMFriendAddRequestCallbackDelegate = new NativeTIm.TIMFriendAddRequestCallbackDelegate(OnIMFriendAddRequestCallbackEvent);
            NativeTIm.tIMLogCallbackDelegate = new NativeTIm.TIMLogCallbackDelegate(OnIMLogCallbackCallbackEvent);
            NativeTIm.tIMMsgUpdateCallbackDelegate = new NativeTIm.TIMMsgUpdateCallbackDelegate(OnIMMsgUpdateCallbackEvent);
            NativeTIm.onTIMSendTIMMsgReportReadedDelegate = new NativeTIm.OnTIMSendTIMMsgReportReadedDelegate(OnSendTIMMsgReportReadedCallBack);
            NativeTIm.onTIMFriendshipGetFriendProfileListCallBackDelegate = new NativeTIm.OnTIMFriendshipGetFriendProfileListCallBackDelegate(OnTIMFriendshipGetFriendProfileListCallBack);
            NativeTIm.onTIMConvGetLocalConvListCallBackDelegate = new NativeTIm.OnTIMConvGetLocalConvListCallBackDelegate(OnTIMConvGetLocalConvListCallBack);
            NativeTIm.onTIMProfileGetUserProfileListCallBackDelegate = new NativeTIm.OnTIMProfileGetUserProfileListCallBackDelegate(OnTIMProfileGetUserProfileListCallBack);

            NativeTIm.onTIMProfileModifySelfUserProfileCallBackDelegate = new NativeTIm.OnTIMProfileModifySelfUserProfileCallBackDelegate(OnTIMProfileModifySelfUserProfileListCallBack);

            NativeTIm.onTIMFriendshipModifyFriendProfileCallBackDelegate = new NativeTIm.OnTIMFriendshipModifyFriendProfileCallBackDelegate(OnTIMFriendshipModifyFriendProfileCallBack);

            NativeTIm.onTIMMsgGetMsgListCallbackDelegate = new NativeTIm.OnTIMMsgGetMsgListCallbackDelegate(OnTIMMsgGetMsgListCallback);
            NativeTIm.onTIMMsgDownloadElemToPathCallbackDelegate = new NativeTIm.OnTIMMsgDownloadElemToPathCallbackDelegate(OnTIMMsgDownloadElemToPathCallback);

            NativeTIm.onTIMMsgSendNewMsgCallBackDelegate = new NativeTIm.OnTIMMsgSendNewMsgCallBackDelegate(OnTIMMsgSendNewMsgCallBack);
            NativeTIm.onTIMFriendshipGetPendencyListCallBackDelegate = new NativeTIm.OnTIMFriendshipGetPendencyListCallBackDelegate(OnTIMFriendshipGetPendencyListCallBack);

            NativeTIm.onTIMFriendshipAddFriendCallBackDelegate = new NativeTIm.OnTIMFriendshipAddFriendCallBackDelegate(OnTIMFriendshipAddFriendCallBack);


        }

        /// <summary>
        /// 注册事件通知
        /// </summary>
        public void AddListenerCallback()
        {
            NativeTIm.TIMAddRecvNewMsgCallback(NativeTIm.tIMRecvNewMsgCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetMsgReadedReceiptCallback(NativeTIm.tIMMsgReadedReceiptCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetMsgRevokeCallback(NativeTIm.tIMMsgRevokeCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetMsgElemUploadProgressCallback(NativeTIm.tIMMsgElemUploadProgressCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetGroupTipsEventCallback(NativeTIm.tIMGroupTipsEventCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetConvEventCallback(NativeTIm.tIMConvEventCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetNetworkStatusListenerCallback(NativeTIm.tIMNetworkStatusListenerCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetKickedOfflineCallback(NativeTIm.tIMKickedOfflineCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetUserSigExpiredCallback(NativeTIm.tIMUserSigExpiredCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetOnAddFriendCallback(NativeTIm.tIMOnAddFriendCallbackDelegate, IntPtr.Zero);
            NativeTIm.TIMSetOnDeleteFriendCallback(NativeTIm.tIMOnDeleteFriendCallbackDelegate, IntPtr.Zero);

            NativeTIm.TIMSetUpdateFriendProfileCallback(NativeTIm.tIMUpdateFriendProfileCallbackDelegate, IntPtr.Zero);

            NativeTIm.TIMSetFriendAddRequestCallback(NativeTIm.tIMFriendAddRequestCallbackDelegate, IntPtr.Zero);

            //NativeTIm.TIMSetLogCallback(NativeTIm.tIMLogCallbackDelegate, IntPtr.Zero);

            NativeTIm.TIMSetMsgUpdateCallback(NativeTIm.tIMMsgUpdateCallbackDelegate, IntPtr.Zero);
        }
        #region 事件通知
        /// <summary>
        /// 设置消息在云端被修改后回传回来的消息更新通知回调
        /// </summary>
        /// <param name="json_msg_array"></param>
        /// <param name="user_data"></param>
        private void OnIMMsgUpdateCallbackEvent(IntPtr jsonMsgArray, IntPtr user_data)
        {
            var json_msg_array = MarshalNativeToManaged(jsonMsgArray);
            Console.WriteLine($"OnIMMsgUpdateCallbackEvent:json_msg_array:{json_msg_array}");
        }
        /// <summary>
        /// 设置日志回调
        /// </summary>
        /// <param name="tIMLogLevel"></param>
        /// <param name="log"></param>
        /// <param name="user_data"></param>
        private void OnIMLogCallbackCallbackEvent(TIMLogLevel tIMLogLevel, string log, IntPtr user_data)
        {
            Console.WriteLine($"OnIMLogCallbackCallbackEvent:tIMLogLevel:{tIMLogLevel};log:{log}");
        }
        /// <summary>
        /// 设置好友添加请求的回调通知
        /// 备注:当前登入用户设置添加好友需要确认时
        /// 如果有用户请求加当前登入用户为好友，会收到好友添加请求的回调
        /// </summary>
        /// <param name="json_friend_profile_update_array"></param>
        /// <param name="user_data"></param>
        private void OnIMFriendAddRequestCallbackEvent(IntPtr jsonFriendProfileUpdateArray, IntPtr user_data)
        {
            try
            {
                ////此方法感觉不需要
                ////因为消息那边也会收到对应的kTIMElem_FriendChange
                //var json_friend_profile_update_array = MarshalNativeToManaged(jsonFriendProfileUpdateArray);
                //List<FriendAddPendency> friendAddPendencies = json_friend_profile_update_array.StringToObject<List<FriendAddPendency>>();
                //if (friendAddPendencies.Count > 0)
                //{
                //    tIMRelationShipCallabck?.OnIMFriendAddRequestNotifyEvent(friendAddPendencies.Select(t=>t.Friend_Add_Pendency_Identifier).ToArray()); 
                //}

            }
            catch (Exception EX)
            {
                Console.WriteLine($"OnIMFriendAddRequestCallbackEvent:{EX.Message}");
                return;

            }

        }
        /// <summary>
        /// 设置更新好友资料的回调通知
        /// </summary>
        /// <param name="json_friend_profile_update_array"></param>
        /// <param name="user_data"></param>
        private void OnTIMUpdateFriendProfileCallbackEvent(IntPtr jsonFriendProfileUpdateArray, IntPtr user_data)
        {
            var json_friend_profile_update_array = MarshalNativeToManaged(jsonFriendProfileUpdateArray);
            Console.WriteLine($"OnTIMUpdateFriendProfileCallbackEvent:{json_friend_profile_update_array}");
        }
        /// <summary>
        /// 处理好友关系后会触发
        /// 设置添加好友的回调通知
        /// </summary>
        /// <param name="json_identifier_array"></param>
        /// <param name="user_data"></param>
        private void OnTIMOnAddFriendCallbackEvent(IntPtr jsonIdentifierArray, IntPtr user_data)
        {
            var json_identifier_array = MarshalNativeToManaged(jsonIdentifierArray);
            Console.WriteLine($"OnTIMOnAddFriendCallbackEvent:{json_identifier_array}");
        }
        /// <summary>
        /// 删除好友
        /// </summary>
        /// <param name="jsonIdentifierArray"></param>
        /// <param name="user_data"></param>
        private void OnOnDeleteFriendCallbackEvent(IntPtr jsonIdentifierArray, IntPtr user_data)
        {
            var json_identifier_array = MarshalNativeToManaged(jsonIdentifierArray);
            Console.WriteLine($"OnTIMOnAddFriendCallbackEvent:{json_identifier_array}");
        }

        /// <summary>
        /// 群事件回调通知
        /// </summary>
        /// <param name="json_group_tip_array"></param>
        /// <param name="user_data"></param>
        private void OnIMGroupTipsEventCallbackEvent(IntPtr jsonGroupTipArray, IntPtr user_data)
        {
            var json_group_tip_array = MarshalNativeToManaged(jsonGroupTipArray);
            Console.WriteLine($"OnIMGroupTipsEventCallbackEvent:{json_group_tip_array}");
        }
        /// <summary>
        /// 用户票据过期回调通知
        /// </summary>
        /// <param name="json_identifier_array"></param>
        /// <param name="user_data"></param>
        private void OnTIMUserSigExpiredCallbackEvent(IntPtr jsonIdentifierArray, IntPtr user_data)
        {
            var json_identifier_array = MarshalNativeToManaged(jsonIdentifierArray);
            Console.WriteLine($"OnTIMUserSigExpiredCallbackEvent:{json_identifier_array}");
        }
        /// <summary>
        /// 消息内元素相关文件上传进度通知
        /// </summary>
        /// <param name="json_msg"></param>
        /// <param name="index"></param>
        /// <param name="cur_size"></param>
        /// <param name="total_size"></param>
        /// <param name="user_data"></param>
        private void OnIMMsgElemUploadProgressCallbackEvent(IntPtr jsonMsg, uint index, uint cur_size, uint total_size, IntPtr user_data)
        {
            var json_msg = MarshalNativeToManaged(jsonMsg);
            Console.WriteLine($"OnIMMsgElemUploadProgressCallbackEvent:{json_msg}");
        }

        /// <summary>
        /// 消息被撤回通知
        /// </summary>
        /// <param name="json_msg_locator_array"></param>
        /// <param name="user_data"></param>
        private void OnIMMsgRevokeCallbackEvent(IntPtr jsonMsgLocatorArray, IntPtr user_data)
        {
            var json_msg_locator_array = MarshalNativeToManaged(jsonMsgLocatorArray);
            Console.WriteLine($"OnIMMsgRevokeCallbackEvent:{json_msg_locator_array}");
        }

        /// <summary>
        /// 消息已读回执通知
        /// </summary>
        /// <param name="json_msg_readed_receipt_array"></param>
        /// <param name="user_data"></param>
        private void OnIMMsgReadedReceiptCallbackEvent(IntPtr jsonMsgReadedReceiptArray, IntPtr user_data)
        {
            var json_msg_readed_receipt_array = MarshalNativeToManaged(jsonMsgReadedReceiptArray);
            Console.WriteLine($"OnIMMsgReadedReceiptCallbackEvent:{json_msg_readed_receipt_array}");
        }

        /// <summary>
        /// 增加接收新消息通知
        /// </summary>
        /// <param name="json_msg_array"></param>
        /// <param name="user_data"></param>
        private void OnTIMRecvNewMsgCallbackEvent(IntPtr jsonMsgArray, IntPtr user_data)
        {

            var json_msg_array = MarshalNativeToManaged(jsonMsgArray);
            if (!string.IsNullOrEmpty(json_msg_array))
            {
                //Console.WriteLine($"OnTIMRecvNewMsgCallbackEvent:{json_msg_array}");
                try
                {
                    var messInfo = JsonConvert.DeserializeObject<List<Message>>(json_msg_array);
                    //如果是自定义消息
                    tIMsgCallback?.OnTIMRecvNewMsg(messInfo);

                }
                catch (Exception ex)
                {
                    Console.WriteLine($"OnTIMRecvNewMsgCallbackEvent:{ex.Message}");
                }
            }
        }


        #endregion
        #endregion


        #region Commom


        public static unsafe void Copy(byte[] source, int sourceOffset, byte[] target,
        int targetOffset, int count)
        {
            // If either array is not instantiated, you cannot complete the copy.
            if ((source == null) || (target == null))
            {
                throw new System.ArgumentException();
            }

            // If either offset, or the number of bytes to copy, is negative, you
            // cannot complete the copy.
            if ((sourceOffset < 0) || (targetOffset < 0) || (count < 0))
            {
                throw new System.ArgumentException();
            }

            // If the number of bytes from the offset to the end of the array is 
            // less than the number of bytes you want to copy, you cannot complete
            // the copy. 
            if ((source.Length - sourceOffset < count) ||
                (target.Length - targetOffset < count))
            {
                throw new System.ArgumentException();
            }

            // The following fixed statement pins the location of the source and
            // target objects in memory so that they will not be moved by garbage
            // collection.
            fixed (byte* pSource = source, pTarget = target)
            {
                // Set the starting points in source and target for the copying.
                byte* ps = pSource + sourceOffset;
                byte* pt = pTarget + targetOffset;

                // Copy the specified number of bytes from source to target.
                for (int i = 0; i < count; i++)
                {
                    *pt = *ps;
                    pt++;
                    ps++;
                }
            }
        }

        /// <summary>
        /// IntPtr 转String
        /// </summary>
        /// <param name="intPtr"></param>
        /// <returns></returns>
        private static string PtrToString(IntPtr intPtr)
        {
            return Marshal.PtrToStringAnsi(intPtr);
        }
        /// <summary>
        /// intptr转string
        /// </summary>
        /// <param name="pNativeData"></param>
        /// <returns></returns>
        public string MarshalNativeToManaged(IntPtr pNativeData)
        {
            if (pNativeData == IntPtr.Zero)
                return null;
            int size = GetNativeDataSize(pNativeData);
            if (size == 0)
                return "";
            byte[] array = new byte[size - 1];
            Marshal.Copy(pNativeData, array, 0, size - 1);
            return Encoding.UTF8.GetString(array);
        }

        /// <summary>
        /// 获取Intptr的长度
        /// </summary>
        /// <param name="ptr"></param>
        /// <returns></returns>
        public int GetNativeDataSize(IntPtr ptr)
        {
            int size = 0;
            for (size = 0; Marshal.ReadByte(ptr, size) > 0; size++)
                ;
            return size;
        }
        #endregion
    }
}
